package com.quanyan.user.service.impl;

import com.google.common.base.Function;
import com.google.common.collect.*;
import com.lefu.commons.utils.Page;
import com.quanyan.api.APIResponse;
import com.quanyan.club.entity.ReqClubMovement;
import com.quanyan.club.entity.RespClubMovement;
import com.quanyan.club.service.ClubOpenService;
import com.quanyan.comment.enums.TaskEnum;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.user.cache.MyRedisTemplate;
import com.quanyan.user.constants.UserConstants;
import com.quanyan.user.mapper.*;
import com.quanyan.user.model.db.*;
import com.quanyan.user.model.vo.DoyenActivity;
import com.quanyan.user.model.vo.VideoLabel;
import com.quanyan.user.model.vo.request.ReqCommentQuery;
import com.quanyan.user.model.vo.request.ReqDynamic;
import com.quanyan.user.model.vo.request.ReqHomePage;
import com.quanyan.user.model.vo.request.ReqNewsPraise;
import com.quanyan.user.model.vo.response.*;
import com.quanyan.user.mq.UserTaskMsg;
import com.quanyan.user.response.ReqImage;
import com.quanyan.user.response.ReqReleaseDynamic;
import com.quanyan.user.response.RespClubDynamicInfo;
import com.quanyan.user.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by zhang on 16/11/8.
 */
@Service
public class UserDynamicServiceImpl implements UserDynamicService {

    private static final Logger logger = LoggerFactory.getLogger(UserDynamicServiceImpl.class);

    @Autowired
    private TbNewsDetailsMapper tbNewsDetailsMapper;

    @Autowired
    private NewsDetailMapper newsDetailMapper;

    @Autowired
    private UserQueryService userQueryService;

    @Autowired
    private TbNewsTopicMapper tbNewsTopicMapper;

    @Autowired
    private TbNewsReportMapper tbNewsReportMapper;

    @Autowired
    private TbUserMapper tbUserMapper;

    @Autowired
    private TbUserInterestMapper tbUserInterestMapper;

    @Autowired
    private TbUserBlacklistMapper tbUserBlacklistMapper;

    @Autowired
    private TbNewsPraiseMapper tbNewsPraiseMapper;

    @Autowired
    private TbUserFollowMapper tbUserFollowMapper;

    @Autowired
    private MyRedisTemplate redisTemplate;

    @Autowired
    private TbNewsImagesMapper tbNewsImagesMapper;

    @Autowired
    private UserFollowService userFollowService;

    @Autowired
    private NewsPraiseService newsPraiseService;

    @Autowired
    private NewsImagesService newsImagesService;

    @Autowired
    private SendMsgService sendMsgService;

    @Autowired
    private MyRedisTemplate myRedisTemplate;

    @Autowired
    private NewsImagesMapper newsImagesMapper;

    @Autowired
    private NewsPraiseMapper newsPraiseMapper;

    @Value("${h5.share.url}")
    private String shareUrl;

    @Value("${h5.video.share.url}")
    private String videoShareUrl;

    @Autowired
    private TopicService topicService;

    @Value("${c.address}")
    private String requestAddress;

    @Autowired
    private HttpClientService httpClientService;

    @Autowired
    private ClubOpenService clubOpenService;

    @Autowired
    private DynamicCommentService dynamicCommentService;

    @Value("${user_default_icon}")
    private String userDefaultIcon;

    @Autowired
    private UserInterestService userInterestService;

    @Autowired
    private UserBlacklistService userBlacklistService;

    @Autowired
    private DiscoveryVideoService discoveryVideoService;

//    @Autowired
//    private SensitiveServiceFacade sensitiveServiceFacade;

    @Override
    public APIResponse<PageObj<List<RespDynamicDetail>>> queryDynamic(ReqDynamic reqDynamic) {
        logger.info("开始获取动态：{}", reqDynamic.toString());
        /*==== 分页  ====*/
        Page page = new Page();
        int pageIndex = reqDynamic.getPageNum() + 1;
        page.setCurrentPage(pageIndex);
        page.setShowCount(reqDynamic.getPageSize());
        List<RespDynamicDetail> lst;//返回结果
        Integer uid = reqDynamic.getUid();//当前登录人
        Integer topicId = reqDynamic.getTopicId(); // 话题id

        List<RespDynamicComment> respCommentList = new ArrayList<>();//动态评论
        List<VideoLabel> videoLabelList = new ArrayList<>();

        /*==== 分类型查询动态  ====*/
        if (UserConstants.DynamicType.loadNewsAll == reqDynamic.getType().intValue()) {//运动圈动态
            lst = newsDetailMapper.findAllloadNewsAll(page);
        } else if (UserConstants.DynamicType.loadNewsMyAttention == reqDynamic.getType().intValue()) {//获取我关注的动态列表
            lst = newsDetailMapper.findAllLoadNewsMyAttention(page, uid);
        } else if (UserConstants.DynamicType.loadNewsMyAttentionDaren == reqDynamic.getType().intValue()) {//获取我关注的达人动态列表
            lst = newsDetailMapper.findAllLoadNewsMyDaren(page, uid);
        } else if (UserConstants.DynamicType.loadNewsMyFans == reqDynamic.getType().intValue()) {// 获取粉丝动态 (占无)
            lst = newsDetailMapper.findAllLoadNewsMyFans(page, uid);
        } else if (UserConstants.DynamicType.loadNewsMyDy == reqDynamic.getType().intValue()) {  // 获取我发布的动态
            lst = newsDetailMapper.findAllLoadNewsMyDy(page, uid);
        } else if (UserConstants.DynamicType.loadNewsTopicDy == reqDynamic.getType().intValue()) {// 获取话题动态
            lst = newsDetailMapper.findAllLoadNewsTopicDy(page, topicId);
        } else if (UserConstants.DynamicType.loadNewsTaDy == reqDynamic.getType().intValue()) { //获取她的动态
            if(uid != null && uid != 0){
                TbUserBlacklist tbUserBlacklist = userBlacklistService.getUserIsBlack(topicId, uid);
                if (tbUserBlacklist != null){ //已经拉黑
                     lst = new ArrayList<>();
                     return APIResponse.returnFail(4005,"你没有权限");
                 }else
                    lst = newsDetailMapper.findAllLoadNewsTaDy(page, topicId);
            }else {
                lst = newsDetailMapper.findAllLoadNewsTaDy(page, topicId);
            }
        } else if (UserConstants.DynamicType.clubDy == reqDynamic.getType().intValue()) { //俱乐部动态
            lst = newsDetailMapper.findAllLoadNewsClubDy(page, reqDynamic.getClubId());
        } else if (UserConstants.DynamicType.discoveryVideoDy == reqDynamic.getType().intValue()) {   //发现视频动态
            lst = newsDetailMapper.findAllDiscoveryVideoDy(page, reqDynamic.getModuleType());
        } else if (UserConstants.DynamicType.choiceDy == reqDynamic.getType().intValue()) { //精选动态
            List<Integer> lstInterestId = userInterestService.userInterests(uid); //用户标签
            lst = newsDetailMapper.findAllChoiceDynamic(page, lstInterestId);
            if (lst.size() < 2)
                lst = newsDetailMapper.findAllChoiceDynamic(page, null);
        } else if (UserConstants.DynamicType.specialVideo == reqDynamic.getType().intValue()) { //首页精选视屏
            lst = newsDetailMapper.findAllSpecialVideoDy(page);
        } else {
            logger.info("没有此类型的动态！");
            return APIResponse.returnFail("没有此类型的动态!");
        }

        if (pageIndex > page.getTotalPage()) {// 大于最后一页
            lst = new ArrayList<>();
            page.setCurrentResult(0);
        }

        if (lst != null && lst.size() > 0) {
            if (UserConstants.DynamicType.discoveryVideoDy == reqDynamic.getType().intValue()
                    || UserConstants.DynamicType.specialVideo == reqDynamic.getType().intValue()) {
                List<Integer> lstCommentId = new ArrayList<>();
                List<Integer> videoIdList = new ArrayList<>();
                //设置评论列表
                // /*==========视屏标签===========*/
                for (RespDynamicDetail dynamicDetail : lst) {
                    if (dynamicDetail.getRespVideo() != null) { //设置视频标签
                        videoIdList.add(dynamicDetail.getRespVideo().getId());
                        lstCommentId.add(dynamicDetail.getId());
                    }
                }
                respCommentList = dynamicCommentService.batchQueryByNewIds(lstCommentId);
                if (videoIdList.size() > 0){
                    videoLabelList = discoveryVideoService.videoLabel(videoIdList);
                    //videoLabelList = discoveryVideoMapper.batchVideoLabelNames(videoIdList);

                }
            }

            List<Integer> lstFid = new ArrayList<>(); //关注,发布动态的用户
            lstFid.addAll(ImmutableSet.copyOf(this.coverListByPropertyUid(lst)).asList());//去重并添加

            List<Integer> lstNewsId = new ArrayList<>();//点赞的用户
            lstNewsId.addAll(this.getNewsId(lst));

            List<Integer> lstDoyenActivityId = new ArrayList<>();//达人活动id
            List<ReqClubMovement> lstClubReq = new ArrayList<>();

            Map<Integer, TbUser> mapTbUser = new HashMap<>();//关注,发布动态的用户
            if (lstFid.size() > 0)
                mapTbUser = userQueryService.batchQueryTbUserMap(lstFid);

            Map<Integer, TbUserFollow> mapUf = new HashMap<>();//查询是否关注
            Map<Integer, TbNewsPraise> mapPraise = new HashMap<>();//查询是否点赞
            if (uid != null && lstFid.size() > 0) {
                mapUf = userFollowService.batchUserFollowMap(uid, lstFid); //关注
                mapPraise = newsPraiseService.findNewsPraiseMap(uid, lstNewsId); //点赞
            }

            /*==========设置图片，点赞信息===========*/
            List<RespDynamicDetail> lstDynamicIdImg = new ArrayList<>();//未在缓存中的动态图片
            List<RespDynamicDetail> lstDynamicIdPraise = new ArrayList<>();//未在缓存中的赞
            ImmutableListMultimap<Integer, ImageObj> topicImgList = null; // 分组后的图片
            ImmutableListMultimap<Integer, RespNewsPraise> lstDynamicPraise = null;//分组后的赞

            for (RespDynamicDetail respDynamicDetail : lst) {
                /************========从缓存查找图片=======**************/
                String keyImg = UserConstants.getDynamicImgKey(respDynamicDetail.getId());
                List<ImageObj> lstImg = (List<ImageObj>) myRedisTemplate.get(keyImg);
                if (lstImg != null) {
                    respDynamicDetail.getImages().addAll(lstImg);
                } else {
                    lstDynamicIdImg.add(respDynamicDetail);
                }
                /************========从缓存查找赞=======**************/
                String keyPraise = UserConstants.getDynamicPraiseKey(respDynamicDetail.getId());
                List<RespNewsPraise> lstPraise = (List<RespNewsPraise>) myRedisTemplate.get(keyPraise);
                if (lstPraise != null) {
                    respDynamicDetail.getPraises().addAll(lstPraise);
                } else {
                    lstDynamicIdPraise.add(respDynamicDetail);
                }

                /************========添加达人活动信息=======**************/
                if (respDynamicDetail.getType().intValue() == UserConstants.DynamicMoudleType.doyen && respDynamicDetail.getActivityId() != 0)
                    lstDoyenActivityId.add(respDynamicDetail.getActivityId());

                /************========添加俱乐部活动信息=======**************/
                if (respDynamicDetail.getType().intValue() == UserConstants.DynamicMoudleType.club && respDynamicDetail.getActivityId() != 0) {
                    ReqClubMovement reqClubMovement = new ReqClubMovement();
                    reqClubMovement.setActivityId(respDynamicDetail.getActivityId());
                    reqClubMovement.setClubId(respDynamicDetail.getClubId());
                    lstClubReq.add(reqClubMovement);
                }

            }
            /************========从DB查找图片=======**************/
            if (lstDynamicIdImg.size() > 0) {
                List<ImageObj> lstImages = newsImagesMapper.findNewsImagesObj(lstDynamicIdImg);
                /****===========按动态分组=============****/
                ImmutableSet digits = ImmutableSet.of(lstImages.toArray());
                Function<ImageObj, Integer> topicImg = new Function<ImageObj, Integer>() {
                    @Override
                    public Integer apply(ImageObj tbNewsImages) {
                        return tbNewsImages.getNewsId();
                    }
                };
                topicImgList = Multimaps.index(digits, topicImg); //分组后
            }

            /************========从DB查找赞=======**************/
            if (lstDynamicIdPraise.size() > 0) {
                List<RespNewsPraise> lstTb = newsPraiseMapper.findPraiseByNewsId(lstDynamicIdPraise);
                /****===========按动态分组=============****/
                ImmutableSet digits = ImmutableSet.of(lstTb.toArray());
                Function<RespNewsPraise, Integer> dynamicPraise = new Function<RespNewsPraise, Integer>() {
                    @Override
                    public Integer apply(RespNewsPraise respNewsPraise) {
                        return respNewsPraise.getNewsId();
                    }
                };
                lstDynamicPraise = Multimaps.index(digits, dynamicPraise); //分组后
            }

            /************========查找达人活动=======**************/
            List<DoyenActivity> lstDoyenActivity = httpClientService.getDyActivity(lstDoyenActivityId);//达人活动
            List<RespClubMovement> lstClubActivity = this.queryClubActivity(lstClubReq);

            for (RespDynamicDetail dy : lst) {
                if (UserConstants.DynamicType.discoveryVideoDy == reqDynamic.getType().intValue()) {
                    dy.setShareUrl(videoShareUrl + (dy.getRespVideo() == null ? "" : dy.getRespVideo().getId()));
                } else {
                    dy.setShareUrl(shareUrl + dy.getId());
                }
                /*==========设置用户信息===========*/
                TbUser tu = mapTbUser.get(dy.getUid());
                if (tu != null) {
                    dy.setNickName(tu.getNickName());
                    ImageObj img = new ImageObj(); //头像
                    img.setImageUrl(tu.getIcon());
                    img.setThumbnailUrl(tu.getIcon());
                    img.setState(1);
                    dy.setUserIcon(img);
                }

                /*==========设置图片===========*/
                if (topicImgList != null) {
                    List<ImageObj> lstTbImg = topicImgList.get(dy.getId());//获取该动态的所有图片
                    if (lstTbImg.size() > 0) {
                        dy.getImages().addAll(lstTbImg);
                        myRedisTemplate.set(UserConstants.getDynamicImgKey(dy.getId()), lstTbImg, 7);
                    }
                }

                /*==========设置赞===========*/
                if (lstDynamicIdPraise.size() > 0) {
                    List<RespNewsPraise> lstDb = lstDynamicPraise.get(dy.getId());
                    if (lstDb != null && lstDb.size() > 0) {
                        String key = UserConstants.getDynamicPraiseKey(dy.getId());
                        myRedisTemplate.set(key, lstDb, 7);
                    }
                }

                /*==========设置是否关注===========*/
                if (mapUf.containsKey(dy.getUid()))
                    dy.setIsFollow(1);
                /*==========设置是否点赞===========*/
                if (mapPraise.containsKey(dy.getId()))
                    dy.setIsPraise(1);

                /*==========达人活动===========*/
                for (DoyenActivity doyenActivity : lstDoyenActivity) {
                    if (dy.getActivityId().intValue() == doyenActivity.getId().intValue())
                        dy.setDoyenActivity(doyenActivity);
                }

                   /*==========俱乐部活动===========*/
                for (RespClubMovement respClubMovement : lstClubActivity) {
                    if (dy.getActivityId().intValue() == respClubMovement.getActivityId().intValue())
                        dy.setRespClubMovement(respClubMovement);
                }

                 /*==========评论===========*/
                for (RespDynamicComment respDynamicComment : respCommentList) {
                    if (respDynamicComment.getDynamicDetailsId().intValue() == dy.getId().intValue() && dy.getDynamicComments().size() < 3) {
                        dy.getDynamicComments().add(respDynamicComment);
                    }
                }

                /*==========视屏标签===========*/
                if (dy.getRespVideo() != null ){
                    for (VideoLabel videoLabel : videoLabelList ){
                        if (videoLabel.getVideoId().intValue() == dy.getRespVideo().getId().intValue()){
                            dy.getRespVideo().getLabelNames().add(videoLabel.getLabelName());
                        }
                    }
                }


            }

            if (UserConstants.DynamicType.choiceDy == reqDynamic.getType().intValue()) {
                for (RespDynamicDetail dy : lst) {
                    for (ImageObj i : dy.getImages()) {
                        if (i != null && i.getChoiceFlg() != null && i.getChoiceFlg() == 1) {
                            dy.getImages().set(0, i);
                        }
                    }
                }
            }
        }
        PageObj<List<RespDynamicDetail>> result = PageObj.create(page.getTotalResult(), page.getCurrentPage(), page.getShowCount(), lst);
        return APIResponse.returnSuccess(result);
    }

    @Override
    public APIResponse<RespDynamicDetail> dynamicDetail(Integer uid, Integer dynamicDetailsId) {
        RespDynamicDetail respDynamicDetail = newsDetailMapper.dynamicDetail(dynamicDetailsId);
        if (respDynamicDetail != null) {
            respDynamicDetail.setShareUrl(shareUrl + dynamicDetailsId);
            /***=========获取发布动态的用户信息=============***/
            Integer newsUid = respDynamicDetail.getUid();
            TbUser tbUser = userQueryService.getUser(newsUid);
            if (tbUser != null) {
                respDynamicDetail.setUid(tbUser.getId());
                ImageObj imageObj = new ImageObj();
                imageObj.setImageUrl(tbUser.getIcon());
                imageObj.setThumbnailUrl(tbUser.getIcon());
                imageObj.setState(1);
                respDynamicDetail.setUserIcon(imageObj);
                respDynamicDetail.setNickName(tbUser.getNickName());
            }
            /***=========获取发布动态图片=============***/
            newsImagesService.setUpDynamicImg(respDynamicDetail);
            /***=========获取赞列表=============***/
            ReqNewsPraise reqNewsPraise = new ReqNewsPraise();
            reqNewsPraise.setPageNum(0);
            reqNewsPraise.setPageSize(2147483647);//显示6个赞
            reqNewsPraise.setDynamicDetailsId(dynamicDetailsId);
            List<RespNewsPraise> lstPraise = newsPraiseService.getDynamicPraiseList(reqNewsPraise).getObject();
            if (lstPraise != null && lstPraise.size() > 0) {
                if (uid != null) {
                    for (RespNewsPraise r : lstPraise) {
                        if (r.getUid().intValue() == uid) {
                            respDynamicDetail.setIsPraise(1);
                            break;
                        }
                    }
                }
                if (lstPraise.size() > 5)
                    respDynamicDetail.setPraises(lstPraise.subList(0, 6));
                else
                    respDynamicDetail.setPraises(lstPraise);
            }
            /***=========获取是否关注改用户=============***/
            if (uid != null) {
                TbUserFollow tbUserFollow = userFollowService.getTbUserFollow(uid, respDynamicDetail.getUid());
                if (tbUserFollow != null)
                    respDynamicDetail.setIsFollow(1);
            }

            List<Integer> lstDoyenActivityId = new ArrayList<>();
            List<ReqClubMovement> lstClubReq = new ArrayList<>();

            /************========添加达人活动信息=======**************/
            if (respDynamicDetail.getType().intValue() == UserConstants.DynamicMoudleType.doyen && respDynamicDetail.getActivityId().intValue() != 0) {
                lstDoyenActivityId.add(respDynamicDetail.getActivityId());
            }

            /************========添加俱乐部活动信息=======**************/
            if (respDynamicDetail.getType().intValue() == UserConstants.DynamicMoudleType.club) {
                ReqClubMovement reqClubMovement = new ReqClubMovement();
                reqClubMovement.setActivityId(respDynamicDetail.getActivityId());
                reqClubMovement.setClubId(respDynamicDetail.getClubId());
                lstClubReq.add(reqClubMovement);
            }
            /************========查找达人活动=======**************/
            List<DoyenActivity> lstDoyenActivity = httpClientService.getDyActivity(lstDoyenActivityId);//达人活动
            List<RespClubMovement> lstClubActivity = this.queryClubActivity(lstClubReq);

            if (lstDoyenActivity.size() > 0)
                respDynamicDetail.setDoyenActivity(lstDoyenActivity.get(0));

            if (lstClubActivity.size() > 0)
                respDynamicDetail.setRespClubMovement(lstClubActivity.get(0));

            newsDetailMapper.updateReadCnt(dynamicDetailsId);//阅读数+1
            return APIResponse.returnSuccess(respDynamicDetail);
        }
        return APIResponse.returnFail("该动态已删除!");
    }


    /**
     * 删除动态
     *
     * @param uid
     * @param dynamicDetailsId
     * @return
     */
    @Override
    @Transactional
    public APIResponse deleteDynamicDetail(Integer uid, Integer dynamicDetailsId) {
        try {
            TbNewsDetails tbNewsDetails = tbNewsDetailsMapper.selectByPrimaryKey(dynamicDetailsId);
            if (tbNewsDetails != null) {
                if (tbNewsDetails.getIsDelete() == Constants.IS_DELETE_TRUE) {
                    logger.info("该动态已经删除！");
                    return APIResponse.returnFail("动态已经删除！");
                }

                if (!uid.equals(tbNewsDetails.getUid())) {
                    logger.info("不能删除别人的动态！");
                    return APIResponse.returnFail("不能删除别人的动态！");
                }

                //删除动态
                int result = newsDetailMapper.deleteNewsDetails(dynamicDetailsId);
                if (result > 0) {
                    Integer topicId = tbNewsDetails.getTopicId();
                    if (topicId != null) {
                        TbNewsDetailsExample example = new TbNewsDetailsExample();
                        TbNewsDetailsExample.Criteria criteria = example.createCriteria();
                        criteria.andTopicIdEqualTo(topicId);
                        criteria.andUidEqualTo(uid);
                        criteria.andIsDeleteNotEqualTo((byte) 1);
                        List<TbNewsDetails> tbNewsDetailses = tbNewsDetailsMapper.selectByExample(example);
                        TbNewsTopic tbNewsTopic = tbNewsTopicMapper.selectByPrimaryKey(topicId);
                        if (tbNewsDetailses != null && tbNewsDetailses.size() > 0) {
                            //更新动态主题回复次数
                            newsDetailMapper.updateNewsTopicReplyTotal(topicId, (byte) 0);
                        } else {
                            //更新动态主题回复次数和参入人数
                            newsDetailMapper.updateNewsTopicPepAndReplyTotal(topicId, (byte) 0);
                            if (tbNewsTopic != null && tbNewsTopic.getRecommFlg() == 1) { // 是推荐的精选话题 精选话题
                                // TODO 设置精选话题列表缓存为无效
                            }
                        }

                    }
                    newsDetailMapper.deleteNewsImages(dynamicDetailsId);
                }


                //设置精选动态列表缓存为无效
                if (tbNewsDetails.getChoiceFlg() == 1) {
                    redisTemplate.delteKey(UserConstants.DynamicKey.NEWS_FIRST_TOURIST_KEY);
                }

            }
        } catch (Exception e) {
            logger.error("删除动态失败：{}", e);
            return APIResponse.returnFail("删除动态失败!");
        }

        return APIResponse.returnSuccess();
    }


    @Override
    public APIResponse reportDynamic(Integer uid, Integer dynamicDetailsId) {
        logger.info("开始举报动态{}", dynamicDetailsId);
        TbNewsDetails tbNewsDetails = tbNewsDetailsMapper.selectByPrimaryKey(dynamicDetailsId);
        if (tbNewsDetails != null) {
            if (tbNewsDetails.getIsDelete() == Constants.IS_DELETE_TRUE) {
                logger.info("改动态已经删除！");
                return APIResponse.returnFail("动态已经删除！");
            }

            TbNewsReportExample tbNewsReportExample = new TbNewsReportExample();
            TbNewsReportExample.Criteria reportCriteria = tbNewsReportExample.createCriteria();
            reportCriteria.andUidEqualTo(Long.valueOf(uid));
            reportCriteria.andNewsIdEqualTo(dynamicDetailsId);
            List<TbNewsReport> lstReport = tbNewsReportMapper.selectByExample(tbNewsReportExample);
            if (lstReport != null && lstReport.size() > 0) {
                logger.info("您已经举报！");
                return APIResponse.returnFail("您已经举报！");
            }

            TbNewsReport tbNewsReport = new TbNewsReport();
            tbNewsReport.setUid(Long.valueOf(uid));
            tbNewsReport.setNewsId(dynamicDetailsId);
            tbNewsReport.setTime(new Date());
            tbNewsReportMapper.insert(tbNewsReport);
            logger.info("举报成功！");
            return APIResponse.returnSuccess();
        }
        return APIResponse.returnFail("动态不存在");
    }


    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public APIResponse addDynamicDetail(ReqReleaseDynamic reqReleaseDynamic) {
        try {
            logger.info("动态发布-----------》start：{}", reqReleaseDynamic.toString());
            Integer uid = reqReleaseDynamic.getUid();
            if (uid == null) {
                return APIResponse.returnFail("发布动态失败");
            }
            Integer topicId = reqReleaseDynamic.getTopicId();
            TbUser tbUser = tbUserMapper.selectByPrimaryKey(uid);
            if (tbUser != null) {
                TbNewsDetails tbNewsDetails = new TbNewsDetails();
                tbNewsDetails.setUid(uid);
                String text = reqReleaseDynamic.getContent();
                tbNewsDetails.setContent(text); //内容
//                if (sensitiveServiceFacade.isExistsKey(text)){
//                    tbNewsDetails.setIsDelete(Constants.IS_DELETE_TRUE);
//                }else{
//                    tbNewsDetails.setIsDelete(Constants.IS_DELETE_FALSE);
//                }
                tbNewsDetails.setPosition(reqReleaseDynamic.getReportAddress());//发布地址
                tbNewsDetails.setLng(reqReleaseDynamic.getLng());
                tbNewsDetails.setLat(reqReleaseDynamic.getLat());
                tbNewsDetails.setType(reqReleaseDynamic.getType().byteValue()); //动态类型 0 app 1：达人
                tbNewsDetails.setTopicId(topicId);//话题
                tbNewsDetails.setActivityId(reqReleaseDynamic.getActivityId());//关联活动id
                tbNewsDetails.setClubId(reqReleaseDynamic.getClubId()); // 俱乐部id
                tbNewsDetails.setReleaseType(reqReleaseDynamic.getReleaseType().byteValue()); // 发布类型
                tbNewsDetails.setIsVideo(reqReleaseDynamic.getPicOrVideo().byteValue());//是否有视屏
                //查询用户在话题下是否有动态
                List<TbNewsDetails> newsDetails = null;
                TbNewsTopic tbNewsTopic = null;
                if (topicId > 0) {
                    tbNewsTopic = tbNewsTopicMapper.selectByPrimaryKey(topicId);
                    TbNewsDetailsExample example = new TbNewsDetailsExample();
                    TbNewsDetailsExample.Criteria criteria = example.createCriteria();
                    criteria.andUidEqualTo(uid);
                    criteria.andTopicIdEqualTo(reqReleaseDynamic.getTopicId());
                    newsDetails = tbNewsDetailsMapper.selectByExample(example);
                }
                // 插入动态数据
                int result = tbNewsDetailsMapper.insertSelective(tbNewsDetails);

                // 插入动态图片
                List<ReqImage> imageObjs = reqReleaseDynamic.getImageObjs();
                List<String> images = reqReleaseDynamic.getImages();
                if (result != 0) {
                    if (imageObjs != null && imageObjs.size() > 0) {
                        newsDetailMapper.batchInsertDynamicImageObjs(imageObjs, tbNewsDetails.getId(), uid);
                    }
                    if (images != null && images.size() > 0) {
                        newsDetailMapper.batchInsertDynamicImages(images, tbNewsDetails.getId(), uid);
                    }
                    // 变更话题统计
                    if (topicId > 0) {
                        if (newsDetails != null && newsDetails.size() > 0) {
                            newsDetailMapper.updateNewsTopicReplyTotal(topicId, (byte) 1);
                        } else {
                            newsDetailMapper.updateNewsTopicPepAndReplyTotal(topicId, (byte) 1);
                            //精选话题缓存失效
                            if (tbNewsTopic != null && tbNewsTopic.getRecommFlg() == 1) {
                                //设置精选话题缓存失效  TODO
                            }
                        }
                    }
                    //发送mq消息，通知任务中心做任务。
                    UserTaskMsg userTaskMsg = new UserTaskMsg();
                    userTaskMsg.setTaskId(TaskEnum.TASK_ENUM__WANT_TO_TALK.getId());
                    userTaskMsg.setUid(uid);
                    sendMsgService.sendUserTaskMsg(userTaskMsg);
                    logger.info("动态发结束end");
                }
            }
        } catch (Exception e) {
            logger.error("发布动态失败！：{}", e);
            return APIResponse.returnFail("发布动态失败!");
        }
        return APIResponse.returnSuccess();
    }


    public RespUserEntity convertTbUserToRespUserEntity(TbUser tbUser) {
        if (tbUser != null) {
            RespUserEntity respUserEntity = new RespUserEntity();
            respUserEntity.setId(tbUser.getId());
            respUserEntity.setUid(tbUser.getId());
            respUserEntity.setNick_name(tbUser.getNickName());
            respUserEntity.setGender(Integer.valueOf(tbUser.getGender()));
            ImageObj imageObj = new ImageObj();
            imageObj.setImageUrl(tbUser.getIcon());
            imageObj.setThumbnailUrl(tbUser.getIcon());
            imageObj.setState(1);
            respUserEntity.setIcon(imageObj);
            return respUserEntity;
        }
        return null;
    }

    @Override
    @Transactional
    public APIResponse<PageObj<List<NewsBaseInfo>>> getFirstNewsList(Integer pageNum, Integer pageSize, Integer uid) {
        if (pageNum == null || pageSize == null) {
            pageNum = 0;
            pageSize = 20;
        }

        TbNewsDetailsExample tbNewsDetailsExample = new TbNewsDetailsExample();
        TbNewsDetailsExample.Criteria newsDetailsCriteria = tbNewsDetailsExample.createCriteria();
        newsDetailsCriteria.andChoiceFlgEqualTo((byte) 1);
        newsDetailsCriteria.andIsDeleteEqualTo((byte) 0);
        com.quanyan.common.Plugin.Page page = new com.quanyan.common.Plugin.Page();
        page.setBegin(pageNum * pageSize);
        page.setLength(pageSize);
        tbNewsDetailsExample.setOrderByClause("seq");
        tbNewsDetailsExample.setPage(page);

        List<NewsBaseInfo> newsBaseInfos = null;
        int count = 0;

        try {
            //游客身份
            if (uid == null || uid <= 0) {
                count = tbNewsDetailsMapper.countByExample(tbNewsDetailsExample);
                if (pageNum == 0) { //缓存游客精选动态首页
                    newsBaseInfos = (List<NewsBaseInfo>) redisTemplate.get(UserConstants.DynamicKey.NEWS_FIRST_TOURIST_KEY);
                    if (newsBaseInfos == null || newsBaseInfos.size() == 0) {
                        List<TbNewsDetails> tbNewsDetailses = tbNewsDetailsMapper.selectByExample(tbNewsDetailsExample);
                        if (tbNewsDetailses == null) {
                            return APIResponse.returnSuccess();
                        }
                        newsBaseInfos = getNewsBaseInfo(uid, tbNewsDetailses);
                        redisTemplate.set(UserConstants.DynamicKey.NEWS_FIRST_TOURIST_KEY, newsBaseInfos, 1);
                    }
                } else {
                    List<TbNewsDetails> tbNewsDetailses = tbNewsDetailsMapper.selectByExample(tbNewsDetailsExample);
                    if (tbNewsDetailses == null) {
                        return APIResponse.returnSuccess();
                    }
                    newsBaseInfos = getNewsBaseInfo(uid, tbNewsDetailses);
                }

            } else { //登录身份
                //获取用户兴趣标签
                TbUserInterestExample tbUserInterestExample = new TbUserInterestExample();
                TbUserInterestExample.Criteria userInterestCriteria = tbUserInterestExample.createCriteria();
                userInterestCriteria.andUidEqualTo(uid);
                userInterestCriteria.andIsObtainEqualTo((byte) 1);
                List<TbUserInterest> userInterests = tbUserInterestMapper.selectByExample(tbUserInterestExample);
                if (userInterests != null && userInterests.size() > 0) {
                    List<Byte> bytes = new ArrayList<>();
                    for (TbUserInterest userInterest : userInterests) {
                        bytes.add(userInterest.getId().byteValue());
                    }
                    //Todo 从缓存中取数据  只缓存第一页数据
                    newsDetailsCriteria.andInterestIdIn(bytes);
                    List<TbNewsDetails> tbNewsDetailses = tbNewsDetailsMapper.selectByExample(tbNewsDetailsExample);

                    if (tbNewsDetailses != null && tbNewsDetailses.size() > 2) { // 首页精选动态不能少于2个
                        count = tbNewsDetailsMapper.countByExample(tbNewsDetailsExample);
                        newsBaseInfos = getNewsBaseInfo(uid, tbNewsDetailses);
                    } else {
                        newsDetailsCriteria.andInterestIdIn(null);
                        List<TbNewsDetails> newsDetailses = tbNewsDetailsMapper.selectByExample(tbNewsDetailsExample);
                        if (newsDetailses == null) {
                            return APIResponse.returnSuccess();
                        }
                        count = tbNewsDetailsMapper.countByExample(tbNewsDetailsExample);
                        newsBaseInfos = getNewsBaseInfo(uid, newsDetailses);
                    }
                } else {
                    //Todo 从缓存中取数据  只缓存第一页数据
                    List<TbNewsDetails> tbNewsDetailses = tbNewsDetailsMapper.selectByExample(tbNewsDetailsExample);
                    count = tbNewsDetailsMapper.countByExample(tbNewsDetailsExample);
                    if (tbNewsDetailses == null) {
                        return APIResponse.returnSuccess();
                    }
                    newsBaseInfos = getNewsBaseInfo(uid, tbNewsDetailses);
                }
            }
        } catch (Exception e) {
            logger.error("获取精选动态列表失败：{}", e);
            return APIResponse.returnFail("获取精选动态列表失败！");
        }

        return APIResponse.returnSuccess(PageObj.create(count, pageNum, pageSize, newsBaseInfos));
    }

    private List<NewsBaseInfo> getNewsBaseInfo(Integer uid, List<TbNewsDetails> tbNewsDetailses) {
        List<NewsBaseInfo> newsBaseInfos = new ArrayList<>();
        for (TbNewsDetails tbNewsDetails : tbNewsDetailses) {
            NewsBaseInfo newsBaseInfo = new NewsBaseInfo();
            newsBaseInfo.setId(tbNewsDetails.getId());
            newsBaseInfo.setUid(tbNewsDetails.getUid());
            newsBaseInfo.setContent(tbNewsDetails.getContent());
            newsBaseInfo.setActivityId(tbNewsDetails.getActivityId());
            newsBaseInfo.setActivityTitle(tbNewsDetails.getActivityTitle());
            newsBaseInfo.setTopicId(tbNewsDetails.getTopicId());
            newsBaseInfo.setType(tbNewsDetails.getType());
            TbNewsTopic tbNewsTopic = tbNewsTopicMapper.selectByPrimaryKey(tbNewsDetails.getTopicId());
            if (tbNewsTopic != null) {
                newsBaseInfo.setTopicName(tbNewsTopic.getName());
            }
            newsBaseInfo.setChoiceFlg(tbNewsDetails.getChoiceFlg());
            newsBaseInfo.setChoiceTime(tbNewsDetails.getChoiceTime());
            newsBaseInfo.setCreateTime(tbNewsDetails.getCreateTime());

            if (uid == null || uid <= 0) {
                newsBaseInfo.setIsPraise((byte) 0);
                newsBaseInfo.setIsFollow((byte) 0);
            } else {
                //过滤用户黑名单
                TbUserBlacklistExample tbUserBlacklistExample = new TbUserBlacklistExample();
                TbUserBlacklistExample.Criteria BlacklistCriteria = tbUserBlacklistExample.createCriteria();
                BlacklistCriteria.andUidEqualTo(tbNewsDetails.getUid());
                BlacklistCriteria.andBlackIdEqualTo(uid);
                List<TbUserBlacklist> blacklists = tbUserBlacklistMapper.selectByExample(tbUserBlacklistExample);
                if (blacklists != null && blacklists.size() > 0) {
                    continue;
                }

                //设置用户是否赞
                TbNewsPraiseExample tbNewsPraiseExample = new TbNewsPraiseExample();
                TbNewsPraiseExample.Criteria praiseCriteria = tbNewsPraiseExample.createCriteria();
                praiseCriteria.andUidEqualTo(uid);
                praiseCriteria.andNewsIdEqualTo(tbNewsDetails.getId());
                praiseCriteria.andTypeEqualTo((byte) 1);
                List<TbNewsPraise> newsPraises = tbNewsPraiseMapper.selectByExample(tbNewsPraiseExample);
                if (newsPraises != null && newsPraises.size() > 0) {
                    newsBaseInfo.setIsPraise((byte) 1);
                } else {
                    newsBaseInfo.setIsPraise((byte) 0);
                }

                // 设置用户是否关注该动态
                TbUserFollowExample tbUserFollowExample = new TbUserFollowExample();
                TbUserFollowExample.Criteria userFollowCriteria = tbUserFollowExample.createCriteria();
                userFollowCriteria.andUidEqualTo(uid);
                userFollowCriteria.andFollowIdEqualTo(tbNewsDetails.getUid());
                userFollowCriteria.andStateEqualTo((byte) 0);
                List<TbUserFollow> userFollows = tbUserFollowMapper.selectByExample(tbUserFollowExample);
                if (userFollows != null && userFollows.size() > 0) {
                    newsBaseInfo.setIsFollow((byte) 1);
                } else {
                    newsBaseInfo.setIsFollow((byte) 0);
                }
            }

            newsBaseInfo.setIsVideo(tbNewsDetails.getIsVideo());
            newsBaseInfo.setLat(tbNewsDetails.getLat());

            newsBaseInfo.setLng(tbNewsDetails.getLng());
            newsBaseInfo.setPosition(tbNewsDetails.getPosition());
            newsBaseInfo.setSumComments(tbNewsDetails.getSumComments());
            newsBaseInfo.setSumPraises(tbNewsDetails.getSumPraises());

            //设置动态图片信息
            TbNewsImagesExample tbNewsImagesExample = new TbNewsImagesExample();
            TbNewsImagesExample.Criteria criteria1 = tbNewsImagesExample.createCriteria();
            criteria1.andNewsIdEqualTo(tbNewsDetails.getId());
            tbNewsImagesExample.setOrderByClause("seq");
            List<TbNewsImages> newsImages = tbNewsImagesMapper.selectByExample(tbNewsImagesExample);
            //将精选图片放在前面
            if (newsImages != null && newsImages.size() > 0) {
                List<TbNewsImages> choiceImages = new ArrayList<>();
                List<TbNewsImages> nonChoiceImages = new ArrayList<>();
                for (TbNewsImages tbNewsImages : newsImages) {
                    if (tbNewsImages.getChoiceFlg() == 1) {
                        choiceImages.add(tbNewsImages);
                    } else {
                        nonChoiceImages.add(tbNewsImages);
                    }
                }
                newsImages.clear();
                newsImages.addAll(choiceImages);
                newsImages.addAll(nonChoiceImages);
            }
            newsBaseInfo.setIamges(newsImages);

            //设置用户信息
            TbUser tbUser = tbUserMapper.selectByPrimaryKey(tbNewsDetails.getUid());
            if (tbUser != null) {
                NewsUserInfo userInfo = new NewsUserInfo();
                userInfo.setId(tbUser.getId());
                userInfo.setIcon(tbUser.getIcon());
                userInfo.setNickName(tbUser.getNickName());
                userInfo.setIsMaster(tbUser.getIsMaster().byteValue());
                newsBaseInfo.setNewsUserInfo(userInfo);
            }

            newsBaseInfos.add(newsBaseInfo);
        }
        return newsBaseInfos;
    }


    @Override
    public APIResponse<List<NewsUserMan>> getFirstPageMans(Integer iNum) {
        List<NewsUserMan> lst = newsDetailMapper.getFirstPageMans(iNum);
        return APIResponse.returnSuccess(lst);
    }

    //list 按属性生成一个新的 list
    public ImmutableMultiset<Integer> getNewsId(List<RespDynamicDetail> lst) {
        return ImmutableMultiset.copyOf(Lists.transform(lst, new Function<RespDynamicDetail, Integer>() {
                    @Override
                    public Integer apply(RespDynamicDetail input) {
                        return input.getId();
                    }
                }
        ));
    }

    //list 按属性生成一个新的 list
    public ImmutableMultiset<Integer> coverListByPropertyActivityId(List<RespDynamicDetail> lst) {
        return ImmutableMultiset.copyOf(Lists.transform(lst, new Function<RespDynamicDetail, Integer>() {
                    @Override
                    public Integer apply(RespDynamicDetail input) {
                        return input.getActivityId();
                    }
                }
        ));
    }

    //list 按属性生成一个新的 list
    public ImmutableMultiset<Integer> coverListByPropertyUid(List<RespDynamicDetail> lst) {
        return ImmutableMultiset.copyOf(Lists.transform(lst, new Function<RespDynamicDetail, Integer>() {
                    @Override
                    public Integer apply(RespDynamicDetail input) {
                        return input.getUid();
                    }
                }
        ));
    }


    //list 按属性生成一个新的 list
    public ImmutableMultiset<Integer> coverListByPropertyInterestId(List<TbUserInterest> lst) {
        return ImmutableMultiset.copyOf(Lists.transform(lst, new Function<TbUserInterest, Integer>() {
                    @Override
                    public Integer apply(TbUserInterest input) {
                        return input.getInterestId();
                    }
                }
        ));
    }


    public APIResponse homePage(ReqHomePage reqHomePage) {
        try {
            Map<String, Object> map = new HashMap<>();
            /**=======获取话题=======**/
            ReqCommentQuery reqCommentQuery = new ReqCommentQuery();
            reqCommentQuery.setPageSize(reqHomePage.getTopicNum());
            List<RespTopicListInfo> lstTopic = topicService.findAllPage(reqCommentQuery).getObject();

            map.put("lstTopic", lstTopic);
            /** ========获取运动圈============= **/
            List<NewsUserMan> lstSportMan = newsDetailMapper.getFirstPageMans(reqHomePage.getSportUserNum());
            map.put("lstSportMan", lstSportMan);
            /** ========精选话题============= **/
            ReqDynamic reqDynamic = new ReqDynamic();
            reqDynamic.setType(UserConstants.DynamicType.choiceDy);
            reqDynamic.setUid(reqHomePage.getUid());
            APIResponse<PageObj<List<RespDynamicDetail>>> response = this.queryDynamic(reqDynamic);
            if (response.isRet() && response.getData() != null)
                map.put("lstSpecialDynamic", response.getData().getItems());
            else {
                map.put("lstSpecialDynamic", new ArrayList<>());
            }

            return APIResponse.returnSuccess(map);
        } catch (Exception e) {
            logger.error("获取首页异常：{}", e);
            return APIResponse.returnFail("系统异常！");
        }
    }

    /**
     * 获取动态最新图片
     *
     * @param currentUid
     * @param uid
     * @param latestNewsImgNum
     * @return
     */
    @Override
    public List<RespImgInfo> getIndexImgList(int currentUid, int uid, int latestNewsImgNum) {
        List<RespImgInfo> list = newsImagesMapper.getIndexDynamicImages(currentUid, uid, latestNewsImgNum);
        return list;
    }

    /**
     * 获取用户动态总数
     *
     * @param currentUid
     * @param uid
     * @return
     */
    @Override
    public int getUserNewsCount(int currentUid, int uid) {
        return newsDetailMapper.getUserNewsCount(currentUid, uid);
    }

    /**
     * 更新仅自己可见动态图片
     *
     * @return
     */
    @Override
    public APIResponse updateDynamicOnlyVisible() {
        TbNewsDetailsExample example = new TbNewsDetailsExample();
        TbNewsDetailsExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo((byte) 2);
        List<TbNewsDetails> list = tbNewsDetailsMapper.selectByExample(example);
        TbNewsImagesExample newsImagesExample;
        TbNewsImages newsImages;
        List<Integer> newsIdList = new ArrayList<>();
        for (TbNewsDetails tbNewsDetails : list) {
            newsImagesExample = new TbNewsImagesExample();
            newsImages = new TbNewsImages();
            newsImagesExample.createCriteria().andNewsIdEqualTo(tbNewsDetails.getId());
            newsImages.setIsDelete((byte) 2);
            tbNewsImagesMapper.updateByExampleSelective(newsImages, newsImagesExample);
            newsIdList.add(tbNewsDetails.getId());
        }
        return APIResponse.returnSuccess(newsIdList);
    }

    /**
     * 获取俱乐部推荐动态
     *
     * @param clubIdList
     * @return
     */
    @Override
    public Map<Integer, RespClubDynamicInfo> getClubRecommendDynamicList(List<Integer> clubIdList) {
        Map<Integer, RespClubDynamicInfo> result = new HashMap<>();

        RespClubDynamicInfo respClubDynamicInfo;
        for (Integer integer : clubIdList) {
            List<TbNewsDetails> tbNewsDetailsList = getRecentDynamic(integer);
            if (tbNewsDetailsList != null && (!tbNewsDetailsList.isEmpty())) {
                TbNewsDetails newsDetails = tbNewsDetailsList.get(0);
                respClubDynamicInfo = new RespClubDynamicInfo();
                respClubDynamicInfo.setClubId(integer);
                respClubDynamicInfo.setCreateTime(newsDetails.getCreateTime());
                respClubDynamicInfo.setContent(newsDetails.getContent());
                respClubDynamicInfo.setDynamicId(newsDetails.getId());
                int uid = newsDetails.getUid();
                TbUser user = userQueryService.getUser(uid);
                if (user != null) {
                    respClubDynamicInfo.setNickName(user.getNickName());
                    respClubDynamicInfo.setIcon(user.getIcon());
                } else {
                    respClubDynamicInfo.setNickName("");
                    respClubDynamicInfo.setIcon(userDefaultIcon);
                }
                result.put(integer, respClubDynamicInfo);
            }
        }
        return result;
    }

    /**
     * 获取俱乐部活动
     *
     * @param reqClubMovements
     * @return
     */
    public List<RespClubMovement> queryClubActivity(List<ReqClubMovement> reqClubMovements) {
        List<RespClubMovement> result = new ArrayList<>();
        try {
            if (reqClubMovements != null && reqClubMovements.size() > 0) {
                APIResponse<List<RespClubMovement>> apiResponse = clubOpenService.searchClubMovmentToUserModele(reqClubMovements);
                if (apiResponse != null && apiResponse.isRet())
                    result = apiResponse.getData();
            }
        } catch (Exception e) {
            logger.error("获取俱乐部活动异常{}", e);
        }
        return result;
    }

    /**
     * 获取最新的俱乐部动态
     *
     * @param clubId
     * @return
     */
    List<TbNewsDetails> getRecentDynamic(int clubId) {
        TbNewsDetailsExample example = new TbNewsDetailsExample();
        example.setOrderByClause("create_time desc limit 0,1");
        TbNewsDetailsExample.Criteria criteria = example.createCriteria();
        criteria.andClubIdEqualTo(clubId);
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbNewsDetails> newsDetailsList = tbNewsDetailsMapper.selectByExample(example);
        return newsDetailsList;
    }

}
